# users.py
# 用户相关路由
from fastapi import APIRouter, Depends, HTTPException, Query 
from sqlalchemy.orm import Session
from app.schemas.user import User as UserSchema

# 导入我们分层架构中的各个组件
from app import crud, schemas
from app.db.session import get_db
# 导入您的统一响应工具
from app.utils.response import success_response

router = APIRouter()

@router.get("/")
def read_users(
    db: Session = Depends(get_db),
    skip: int = Query(0, description="要跳过的记录数量，用于分页"),
    limit: int = Query(100, description="要返回的最大记录数量，不能超过100"),
):
    """
    获取用户列表
    """
    users = crud.user.get_multi(db, skip=skip, limit=limit)
    # 使用您的成功响应包装器
    return success_response(data=users)

@router.post("/")
def create_user(
    *,
    db: Session = Depends(get_db),
    user_in: schemas.user.UserCreate,
):
    """
    创建新用户
    """
    user = crud.user.get_by_email(db, email=user_in.email)
    if user:
        # 失败出口：拉响警报，剩下的交给全局处理器
        raise HTTPException(
            status_code=400,
            detail="The user with this email already exists in the system.",
        )
    
    new_user = crud.user.create(db=db, obj_in=user_in)
    new_user_data = UserSchema.model_validate(new_user)
    # 成功出口：使用成功响应包装器
    return success_response(data=new_user_data)

@router.get("/{user_id}")
def read_user_by_id(
    user_id: int,
    db: Session = Depends(get_db),
):
    """
    根据 ID 获取单个用户信息
    """
    user = crud.user.get(db, id=user_id)
    if not user:
        # 失败出口：拉响警报，剩下的交给全局处理器
        raise HTTPException(status_code=404, detail="User not found")
    user_data = UserSchema.model_validate(user)
    # 成功出口：使用成功响应包装器
    return success_response(data=user_data)